class DigitalLife {
    constructor() {
        this.textData = '';
        this.audioRecordings = [];
        this.images = [];
        this.isRecording = false;
        this.mediaRecorder = null;
        this.audioChunks = [];
        this.consciousnessData = null;
        
        this.initializeElements();
        this.initializeEventListeners();
    }

    initializeElements() {
        // 文本输入
        this.textArea = document.querySelector('.upload-section textarea');
        this.textUploadBtn = document.querySelector('.upload-section .upload-btn');
        
        // 录音
        this.recordBtn = document.querySelector('.record-btn');
        this.recordStatus = document.querySelector('.record-status');
        this.voiceList = document.querySelector('.voice-list');
        
        // 图片上传
        this.imageInput = document.getElementById('imageUpload');
        this.imagePreview = document.querySelector('.image-preview');
        
        // 进度条
        this.progressContainer = document.querySelector('.upload-progress-container');
        this.progressInner = document.querySelector('.progress-inner');
        this.progressStatus = document.querySelector('.progress-status');

        // 意识体生成
        this.generateContainer = document.querySelector('.generate-container');
        this.generateBtn = document.querySelector('.generate-btn');
    }

    initializeEventListeners() {
        // 文本上传
        this.textUploadBtn.addEventListener('click', () => this.handleTextUpload());
        
        // 录音控制
        this.recordBtn.addEventListener('click', () => this.toggleRecording());
        
        // 图片上传
        this.imageInput.addEventListener('change', (e) => this.handleImageUpload(e));

        // 意识体生成
        this.generateBtn.addEventListener('click', () => this.downloadConsciousness());
    }

    async handleTextUpload() {
        const text = this.textArea.value.trim();
        if (!text) {
            alert('请输入文本内容');
            return;
        }
        
        this.textData = text;
        this.textUploadBtn.disabled = true;
        this.textUploadBtn.innerHTML = '<i class="fas fa-check"></i>已上传';
        
        if (this.isReadyToGenerate()) {
            this.generateDigitalLife();
        }
    }

    async toggleRecording() {
        if (!this.isRecording) {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                this.mediaRecorder = new MediaRecorder(stream);
                this.audioChunks = [];
                
                this.mediaRecorder.ondataavailable = (e) => {
                    this.audioChunks.push(e.data);
                };
                
                this.mediaRecorder.onstop = () => {
                    const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });
                    this.addAudioToList(audioBlob);
                };
                
                this.mediaRecorder.start();
                this.isRecording = true;
                this.recordBtn.classList.add('recording');
                this.recordStatus.textContent = '录音中...点击停止';
            } catch (err) {
                console.error('录音失败:', err);
                alert('无法访问麦克风');
            }
        } else {
            this.mediaRecorder.stop();
            this.isRecording = false;
            this.recordBtn.classList.remove('recording');
            this.recordStatus.textContent = '点击开始录音';
        }
    }

    addAudioToList(audioBlob) {
        const audioUrl = URL.createObjectURL(audioBlob);
        this.audioRecordings.push(audioBlob);
        
        const audioElement = document.createElement('div');
        audioElement.className = 'voice-item';
        audioElement.innerHTML = `
            <i class="fas fa-play"></i>
            <audio src="${audioUrl}" controls></audio>
            <span>录音 ${this.audioRecordings.length}</span>
        `;
        
        this.voiceList.appendChild(audioElement);
        
        if (this.isReadyToGenerate()) {
            this.generateDigitalLife();
        }
    }

    handleImageUpload(event) {
        const files = Array.from(event.target.files);
        files.forEach(file => {
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.images.push(file);
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    this.imagePreview.appendChild(img);
                };
                reader.readAsDataURL(file);
            }
        });
        
        if (this.isReadyToGenerate()) {
            this.generateDigitalLife();
        }
    }

    isReadyToGenerate() {
        return this.textData && this.audioRecordings.length > 0 && this.images.length > 0;
    }

    async generateDigitalLife() {
        this.progressContainer.style.display = 'block';
        this.progressStatus.textContent = '正在处理数据...';
        
        try {
            // 创建FormData对象
            const formData = new FormData();
            formData.append('text', this.textData);
            this.audioRecordings.forEach((blob, index) => {
                formData.append(`audio_${index}`, blob);
            });
            this.images.forEach((file, index) => {
                formData.append(`image_${index}`, file);
            });
            
            // 模拟上传进度
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += 5;
                if (progress <= 100) {
                    this.progressInner.style.width = `${progress}%`;
                    this.progressStatus.textContent = `处理中...${progress}%`;
                }
            }, 500);
            
            try {
                // 调用后端API生成prompt
                const response = await fetch('http://localhost:5000/api/generate_prompt', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        text: this.textData,
                        hasVoice: this.audioRecordings.length > 0,
                        hasImage: this.images.length > 0
                    })
                });

                if (!response.ok) {
                    throw new Error('Prompt生成失败');
                }

                const data = await response.json();
                this.consciousnessData = {
                    version: "1.0",
                    timestamp: new Date().toISOString(),
                    consciousness: {
                        text: {
                            content: this.textData,
                            prompt: data.prompt,
                            embeddings: data.embeddings || this.generateEmbeddings(this.textData),
                            keywords: data.keywords || this.extractKeywords(this.textData)
                        },
                        voice: {
                            samples: this.audioRecordings.map((_, index) => ({
                                id: index + 1,
                                parameters: this.generateVoiceParameters()
                            }))
                        },
                        appearance: {
                            images: this.images.map((_, index) => ({
                                id: index + 1,
                                features: this.generateImageFeatures()
                            }))
                        }
                    }
                };

            } catch (error) {
                console.error('Prompt生成失败:', error);
                // 如果API调用失败,使用本地生成的数据
                this.generateConsciousnessData();
            }
            
            clearInterval(progressInterval);
            this.progressInner.style.width = '100%';
            this.progressStatus.textContent = '数字生命生成完成！';
            
            // 显示生成按钮
            this.generateContainer.style.display = 'block';
            
            // 初始化对话系统
            this.initializeChat();
            
        } catch (error) {
            console.error('生成数字生命失败:', error);
            this.progressStatus.textContent = '处理失败，请重试';
        }
    }

    initializeChat() {
        const chatContainer = document.querySelector('.chat-container');
        const chatMessages = document.querySelector('.chat-messages');
        const chatInput = document.querySelector('.chat-input input');
        const sendButton = document.querySelector('.chat-input button');

        // 显示欢迎消息
        chatMessages.innerHTML = `
            <div class="message system">
                <p>您的数字生命已经准备就绪,开始对话吧!</p>
            </div>
        `;
        
        // 显示对话界面
        chatContainer.style.display = 'block';

        // 添加发送消息的事件监听
        const sendMessage = async () => {
            const message = chatInput.value.trim();
            if (!message) return;

            // 添加用户消息到界面
            chatMessages.innerHTML += `
                <div class="message user">
                    <p>${message}</p>
                </div>
            `;

            chatInput.value = '';
            chatMessages.scrollTop = chatMessages.scrollHeight;

            try {
                // 调用对话API
                const response = await fetch('http://localhost:5000/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        consciousness: this.consciousnessData
                    })
                });

                if (!response.ok) {
                    throw new Error('对话请求失败');
                }

                const data = await response.json();
                
                // 添加AI回复到界面
                chatMessages.innerHTML += `
                    <div class="message ai">
                        <p>${data.response}</p>
                    </div>
                `;
                
                chatMessages.scrollTop = chatMessages.scrollHeight;

            } catch (error) {
                console.error('对话失败:', error);
                chatMessages.innerHTML += `
                    <div class="message system">
                        <p>对话出现错误,请稍后重试</p>
                    </div>
                `;
            }
        };

        sendButton.addEventListener('click', sendMessage);
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    }

    generateConsciousnessData() {
        // 生成意识体数据结构
        this.consciousnessData = {
            version: "1.0",
            timestamp: new Date().toISOString(),
            consciousness: {
                text: {
                    content: this.textData,
                    embeddings: this.generateEmbeddings(this.textData),
                    keywords: this.extractKeywords(this.textData)
                },
                voice: {
                    samples: this.audioRecordings.map((_, index) => ({
                        id: index + 1,
                        parameters: this.generateVoiceParameters()
                    }))
                },
                appearance: {
                    images: this.images.map((_, index) => ({
                        id: index + 1,
                        features: this.generateImageFeatures()
                    }))
                }
            }
        };
    }

    // 生成文本嵌入向量(示例)
    generateEmbeddings(text) {
        // 实际应用中应该调用专门的文本嵌入模型
        return Array(128).fill(0).map(() => Math.random());
    }

    // 提取关键词(示例)
    extractKeywords(text) {
        // 实际应用中应该使用NLP模型提取关键词
        return text.split(/\s+/).slice(0, 10);
    }

    // 生成声音参数(示例)
    generateVoiceParameters() {
        return {
            pitch: Math.random() * 100,
            speed: Math.random() * 2 + 0.5,
            timbre: Math.random() * 100,
            energy: Math.random() * 100
        };
    }

    // 生成图像特征(示例)
    generateImageFeatures() {
        return {
            faceShape: Math.floor(Math.random() * 5),
            skinTone: Math.floor(Math.random() * 10),
            eyeColor: Math.floor(Math.random() * 5),
            hairStyle: Math.floor(Math.random() * 8)
        };
    }

    downloadConsciousness() {
        if (!this.consciousnessData) {
            alert('请先完成意识上传');
            return;
        }

        // 创建Blob对象
        const blob = new Blob(
            [JSON.stringify(this.consciousnessData, null, 2)], 
            { type: 'application/json' }
        );
        
        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `consciousness_${new Date().getTime()}.json`;
        
        // 触发下载
        document.body.appendChild(a);
        a.click();
        
        // 清理
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
}

// 创建数字生命实例
window.digitalLife = new DigitalLife(); 